﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Presentation.Services;
using Portal.Presentation.Providers;
using Portal.Model;

namespace Portal.Presentation.Controllers
{
    /// <summary>
    /// Class <see cref="ControllerBase"/> define base controller
    /// </summary>
    public abstract class ControllerBase : Controller
    {

        #region Fields
        private readonly ISessionService _session;
        private readonly ISecurityProvider _security;
        #endregion

        #region Properties

        /// <summary>
        /// Gets the SessionService.
        /// </summary>
        /// <returns>SessionService</returns>
        public ISecurityProvider SecurityProvider
        {
            get { return _security; }
        }

        #endregion

        #region .ctor
        /// <summary>
        /// Initializes a new instance of the <see cref="ControllerBase"/> class.
        /// </summary>
        /// <param name="security">The security.</param>
        /// <exception cref="System.ArgumentNullException">security</exception>
        public ControllerBase(ISecurityProvider security, ISessionService session)
        {
            if (security == null)
            {
                throw new ArgumentNullException("security");
            }
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            _session = session;
            _security = security;
        }
        #endregion

        #region Methods

        /// <summary>
        /// Returns currently loggin user
        /// </summary>
        /// <returns></returns>
        public IUser GetCurrentUser()
        {
            return SecurityProvider.GetUser(GetLogon());
        }

        /// <summary>
        /// Gets the logon of current user.
        /// </summary>
        /// <returns></returns>
        public string GetLogon()
        {

            if (Request == null || Request.LogonUserIdentity == null)
            {
                return null;
            }
            return Request.LogonUserIdentity.Name;
        }
        #endregion

        #region Events
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            _session.Initialize(filterContext.HttpContext.Session);
        }
        #endregion
    }
}